package cn.cuilan.httpfileserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * HTTP文件服务器
 *
 * @author zhang.yan
 * @date 2020/3/21
 */
public class HttpFileServer {

    /**
     * 启动HTTP文件服务器
     *
     * @param host              绑定IP或域名
     * @param port              端口
     * @param url               代理目录
     * @param showHiddenFile    是否显示隐藏文件
     * @param showInvaildSymbol 是否显示非法字符
     * @throws InterruptedException
     */
    public void run(final String host, final int port, final String url,
                    boolean showHiddenFile, boolean showInvaildSymbol) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup worderGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boosGroup, worderGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("http-decoder", new HttpRequestDecoder());
                            pipeline.addLast("http-aggregator", new HttpObjectAggregator(65535));
                            pipeline.addLast("http-encoder", new HttpResponseEncoder());
                            pipeline.addLast("http-chunked", new ChunkedWriteHandler());
                            pipeline.addLast("fileServerHandler", new HttpFileServerHandler(url, showHiddenFile, showInvaildSymbol));
                        }
                    });
            ChannelFuture future = bootstrap.bind(host, port).sync();
            System.out.println("HTTP 文件服务器启动成功: http://" + host + ":" + port + url);
            future.channel().closeFuture().sync();
        } finally {
            boosGroup.shutdownGracefully();
            worderGroup.shutdownGracefully();
        }
    }
}
